package com.malljelly.study.controller;

import com.alibaba.fastjson.JSONObject;
import com.malljelly.study.properties.SecurityProperties;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by 骑着蜗牛去旅行 on 2018/8/18.
 */

@RestController
@Slf4j
public class BrowserSecurityController {


    @GetMapping("/user")
    public String getUsers() {
        return "Hello Spring Security";
    }

    private RequestCache requestCache = new HttpSessionRequestCache();  //请求缓存
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); //重定向



    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 当需要身份认证时，跳转到这里
     *
     */
    @RequestMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public com.alibaba.fastjson.JSONObject requireAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        JSONObject result = new JSONObject();
        SavedRequest savedRequest = requestCache.getRequest(request, response);

        if (savedRequest != null) {
            String targetUrl = savedRequest.getRedirectUrl();
            log.info("引发跳转的请求是:" + targetUrl);
            if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {
                redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
            }
        }
        result.put("code", 401);
        result.put("msg", "访问的服务需要身份认证，请引导用户到登录页");
        return result;
    }

    /**
     * 新增保存会员
     */
    @ApiOperation(value = "保存会员")
    @PostMapping("saveMember")
    public com.alibaba.fastjson.JSONObject saveMember()
    {
        JSONObject result = new JSONObject();
        result.put("code", 0);
        return result;

    }

    /**
     * 获取登录用户信息
     * @param user
     * @return
     */
    @GetMapping("/me")
    public Object getCurrentUser(@AuthenticationPrincipal UserDetails user) {
        return user;
    }

}
